package com.paic.tpa;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class MenuService {

	static {
		System.out.println("MenuService is loaded...");
	}
	
	@Value("${subsystemNames}")
	String[] subsystemNames;
	
	@Autowired
    RestTemplate restTemplate;
	
	@HystrixCommand(fallbackMethod="getMenusFallback")
	public String getMenus(String roles) {
		String result = "";
//		JSONObject jsAll = new JSONObject();
		JSONArray array = new JSONArray();
		for (String s : subsystemNames){
//        return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
//			try {
				ResponseEntity<String> entity = restTemplate.getForEntity("http://"+s+"/menus/"+roles, String.class);
				result = entity.getBody();
				System.out.println(s);
				System.out.println(result);
				JSONArray js = JSONArray.fromObject(result);
//				JSONObject js = JSONObject.fromObject(result);
				array.add(js);
//			} catch (Exception ex) {
//				System.out.println(ex.toString());
//			}
		}
		return array.toString();
    }
	
	public String getMenusFallback(String roles, Throwable e) {
		return "error: " + e.toString();
	}
}
